import {body, description, path, query, request, summary, tagsAll} from "koa-swagger-decorator-fork";
import {cleanUrl} from "../../utils/common";
import {addShareLink, getShareByFileType, getShareByPath, delShare} from "../../utils/nc/share";
import {getFileById} from "../../utils/nc/file";
import {FileSchema} from '../../schema/index'
import migrate from "../../migrate";
import config from "config";
import {parseFilePath} from "../../utils/common"
import responseMapper from "../../utils/responseMapper";
const nodepath = require('path')

const publicPath = config.get('nextcloud.share_path')

@tagsAll(['ShareFile'])
export default class ShareFileRouter {
    @request('POST', '/shares')
    @summary('share file by name')
    @description('发布文件')
    @body(FileSchema)
    static async share(ctx) {
        let {name,path} = ctx.request.body,share,
            groupShare = ctx.request.body.groupShare?(ctx.request.body.groupShare==true):false
        path = path || '/'
        path = cleanUrl(`${publicPath}${path}/${name}`)
        if(!groupShare){
            share = await getShareByPath(ctx.user,path)
            if(!share){
                share = await addShareLink(ctx.user,path,groupShare)
            }else{
                throw new Error(`public share with id ${share.id} already created`)
            }
        }else{
            share = await addShareLink(ctx.user,path,groupShare)
        }
        ctx.body = {basename:name,path:ctx.request.body.path,id:share.id,token:share.token}
    }

    @request('GET', '/shares')
    @summary('find shares')
    @description('查询发布列表')
    @query({
        pattern: {type: 'string',example:'lnkg'}
    })
    static async getShares(ctx) {
        let pattern = ctx.query.pattern?.split(',')||[]
        let files = await getShareByFileType(ctx.user,pattern),fileItem,result=[]
        if(files&&files.length){
            for(let file of files){
                if(file.file_target===publicPath){
                    continue
                }
                file.path = decodeURIComponent(file.path.replace(publicPath,'')||'/')
                file.basename = decodeURIComponent(nodepath.basename(file.file_target))
                fileItem = (({ path,basename,id,token,file_source }) => ({ path,basename,id,token,file_source }))(file);
                result.push(fileItem)
            }
        }
        ctx.body = responseMapper.wrapResponse(ctx,result,'/',false);
    }

    @request('GET', '/shares/{name}')
    @summary('get share by name')
    @description('查询public发布内容')
    @path({ name: { type: 'string', required: true } })
    @query({
        path: { type: 'string'}
    })
    static async getShareByName(ctx) {
        let filename = ctx.params.name,data,share,result,path = ctx.query.path || '/'
        data = await ctx.client.getFileContents(`/files/${ctx.user.id}${publicPath}${path}/${filename}`,{format:'text'});
        path = cleanUrl(`${publicPath}${path}/${filename}`)
        share = await getShareByPath(ctx.user,path)
        if(!share){
            throw new Error('no public share find')
        }
        result = {...share,data,params:['lightbox=1','highlight=0000ff','layers=1','nav=1',`title=${filename}`]}
        ctx.body = result
    }

    @request('DELETE', '/shares/{id}')
    @summary('delete share by share id')
    @description('删除指定发布')
    @path({ id: { type: 'string', required: true } })
    static async delShare(ctx) {
        await delShare(ctx.user,ctx.params.id)
        ctx.body = {}
    }

    @request('GET', '/shares/public/{id}')
    @summary('get public share by share id')
    @description('查询指定公开发布内容')
    @path({ id: { type: 'string', required: true } })
    static async getPublicShare(ctx) {
        let id = decodeURIComponent(ctx.params.id),data
        try{
            data = await getFileById(id)
        }catch(err){
            data = await migrate.getLegacyShare(id)
        }
        ctx.body = {data}
    }
}
